package com.cdqidi.core.weixinmanager.util;

import com.cdqidi.exception.ApiException;
import com.jfinal.springboot.weixin.annotation.ApiType;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.wxaapp.WxaConfigKit;
import org.springframework.util.StringUtils;

import java.util.function.Supplier;

/**
 * 调用微信接口前往线程变量中set appId
 *
 * @author sjk
 */
public class CallWxUtil {
    private CallWxUtil() {

    }

    public static <T> T callInterface(String appId, ApiType apiType, Supplier<T> supplier) {
        if (!StringUtils.hasLength(appId)) {
            throw new ApiException("小程序appId不能为空");
        }
        if (ApiType.WX == apiType) {
            try {
                ApiConfigKit.setThreadLocalAppId(appId);
                return supplier.get();
            } finally {
                ApiConfigKit.removeThreadLocalAppId();
            }
        }
        if (ApiType.WXA == apiType) {
            try {
                WxaConfigKit.setThreadLocalAppId(appId);
                return supplier.get();
            } finally {
                WxaConfigKit.removeThreadLocalAppId();
            }
        }
        throw new ApiException("类型不匹配");
    }
}
